package org.community.loginsvc.service.detailservice.userinfo;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(
        isolation = Isolation.REPEATABLE_READ
)
@Slf4j
public class UploadUserInfoToRedisService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Value("${service.redis.duration}")
    private long expireTime;

    public void uploadToRedisByMap(Map<String,Object> userInfoMap,Integer userId){

        for(Map.Entry<String,Object> entry: userInfoMap.entrySet()){
            //认证库存一份
            StpUtil.getSessionByLoginId(userId).set(entry.getKey(),entry.getValue());
            //业务数据库存一份

        }
        this.uploadToServiceRedis(userInfoMap,userId);
    }

    public void uploadToServiceRedis(Map<String,Object> userInfoMap,Integer userId){
        String infoId;
        //如果没有，则新建
        if(Boolean.FALSE.equals(stringRedisTemplate.hasKey(userId.toString()))){
            infoId = String.valueOf(UUID.randomUUID());
            stringRedisTemplate.opsForValue().set(userId.toString(),infoId ,expireTime, TimeUnit.MINUTES);
            stringRedisTemplate.opsForValue().set(infoId, JSON.toJSONString(userInfoMap),expireTime, TimeUnit.MINUTES);
            return;
        }
        //先获取原来的redis数据集
        infoId = stringRedisTemplate.opsForValue().get(Integer.toString((Integer) userId));
        assert infoId != null;
        //覆盖存储
        stringRedisTemplate.opsForValue().set(userId.toString(),infoId ,expireTime, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(infoId, JSON.toJSONString(userInfoMap),expireTime, TimeUnit.MINUTES);
    }


}
